package com.sc.form_authentation.config;

import com.sc.form_authentation.filter.VerificationCodeFilter;
import com.sc.form_authentation.util.MyAuthenticationFailureHandler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.provisioning.JdbcUserDetailsManager;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.sql.DataSource;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.function.Function;


@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
/*        http.authorizeRequests()
                .anyRequest()
                .authenticated()
                .and()
                .formLogin()
                .loginPage("http://localhost/login.html")
                .loginProcessingUrl("http://localhost/login.html") //处理登录的handler
                .successHandler((request, response, authentication) -> {
                    response.setContentType("application/json;charset=UTF-8");
                    PrintWriter writer = response.getWriter();
                    writer.write("'error_code:0','message:欢迎登录系统'");
                })//指定成功后处理的逻辑
                .failureHandler(new AuthenticationFailureHandler() {
                    @Override
                    public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws IOException, ServletException {
                        response.setContentType("application/json;charset=UTF-8");
                        response.setStatus(404);
                        PrintWriter writer = response.getWriter();
                        //输出失败原因
                        writer.write("{'error_code:401','name:'"+exception.getClass()
                        +"',message:'"+exception.getMessage()+"}");
                    }
                })
                .permitAll()
                .and()
                .csrf()
                .disable();*/
        http.authorizeRequests()
                .antMatchers("/admin/api/**").hasRole("ADMIN")
                .antMatchers("/user/api/**").hasRole("USER")
                .antMatchers("/app/api/**")
                .permitAll()
                .antMatchers("/captcha").permitAll()
                .anyRequest()
                .authenticated()
                .and()
                .formLogin()
                .loginPage("http://localhost/login.html")
                .loginProcessingUrl("/auth/form")
                 //指定成功后处理的逻辑
                .failureHandler(new MyAuthenticationFailureHandler())
                .and()
                .csrf()
                .disable();
        //将过滤器添加到UsernamePasswordAuthenticationFilter之前
        http.addFilterBefore(new VerificationCodeFilter(), UsernamePasswordAuthenticationFilter.class);
    }


    @Autowired
    private UserDetailsService userDetailsService;

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(userDetailsService).passwordEncoder(new BCryptPasswordEncoder());
    }
/*    @Bean
    public BCryptPasswordEncoder bCryptPasswordEncoder(){
        return new BCryptPasswordEncoder();
    }*/

    /*    @Autowired
    private DataSource dataSource;*/
/*    @Bean
    public UserDetailsService userDetailsService(DataSource dataSource,BCryptPasswordEncoder encoder){
        JdbcUserDetailsManager manager = new JdbcUserDetailsManager();
        manager.setDataSource(dataSource);
        String userPwd = encoder.encode("user");
        String adminPwd = encoder.encode("admin");
        manager.createUser(User.withUsername("user").password(userPwd).roles("USER").build());
        manager.createUser(User.withUsername("admin").password(adminPwd).roles("Admin").build());
        return manager;
    }*/
}
